import {Component, Inject} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {GnMessageService} from "geminis-ng";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material";

@Component({
  selector: 'gn-manage-administrator-role',
  templateUrl: './administrator-role.component.html'
})
export class AdministratorRoleComponent {

  roles: any[] = [];
  selectedRoles: string[] = [];

  constructor(private httpClient: HttpClient,
              private messageService: GnMessageService,
              private dialog: MatDialogRef<void>,
              @Inject(MAT_DIALOG_DATA) private adminId: string) {
    httpClient.get('/MANAGE-SERVICE/login/manageRole')
      .subscribe((roles: any[]) => {
        this.roles = roles;
      });

    const pageInfo = {
      'pageIndex': 0,
      'pageSize': 1,
      'filterGroup': {filters: [{'field': 'id', 'compareType': '=', 'value': this.adminId}]},
      'includes': ['roles']
    };

    this.httpClient.post('/MANAGE-SERVICE/administrators', pageInfo)
      .subscribe((admin: any) => {
        this.selectedRoles = admin.content[0].roles.map(role => role.id);
      }, error => {
        this.messageService.error({message: '获取角色信息错误', error: error.error});
      });
  }

  confirm(): void {
    this.httpClient.put('/MANAGE-SERVICE/administrators/' + this.adminId + '/role', this.selectedRoles)
      .subscribe(() => {
        this.messageService.success('角色已保存');
        this.dialog.close('confirmed');
      }, error => {
        this.messageService.error({message: '保存角色错误', error: error.error});
      });
  }

}
